<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .list {
            width: 200px;
            height: 150px;
            background-color: aqua;
            overflow: auto;
        }

        .news {
            height: 30px;
        }
    </style>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="text"></div>
    <!-- react 核心库 -->
    <script type="text/javascript" src="../js/react.development.js"></script>
    <!-- 引入react-dom 支持react dom 操作 -->
    <script type="text/javascript" src="../js/react-dom.development.js"></script>

    <!-- 蒋jsx装换为js  -->
    <script type="text/javascript" src="../js/babel.min.js"></script>
    <script type="text/babel">
        class NewList extends React.Component {
            //定义一个新的状态
            state = { newsArr: [] }
            //组件渲染之后调用的钩子
            componentDidMount() {
                setInterval(() => {
                    //获取原状态
                    const { newsArr } = this.state
                    //模拟一条新闻
                    const news = '新闻' + (newsArr.length + 1)
                    //更新状态
                    this.setState({ newsArr: [news, ...newsArr] })
                }, 1000);
            }
            //更新之前获取快照
            getSnapshotBeforeUpdate() {
                return this.refs.list.scrollHeight
            }
            //更新的时候触发的钩子
            componentDidUpdate(preProps, preState, height) {
                this.refs.list.scrollTop += this.refs.list.scrollHeight - height
            }
            render() {
                return (
                    <div className="list" ref="list">
                       {
                          this.state.newsArr.map((n,index)=>{
                              return <div key={index} className="news"> {n}</div>
                          })
                       }
                    </div>
                )
            }
        }
        ReactDOM.render(<NewList />, document.getElementById('text'))
    </script>
</body>

</html>